/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentanaPrincipal.java
 *
 * Created on 14/12/2009, 11:10:57 PM
 */

package servidorchat;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrador
 */
public class VentanaPrincipal extends javax.swing.JFrame {

    /** Creates new form VentanaPrincipal */
    public VentanaPrincipal() {
        initComponents();
        initOtrasPropiedades();
        anadirTrayIcon();
        
    }

    private void  initOtrasPropiedades(){
        this.txtEstado.setVisible(false);
        this.setLocationRelativeTo(this);
        this.setResizable(false);
        addWindowStateListener(new java.awt.event.WindowStateListener() {
            public void windowStateChanged(java.awt.event.WindowEvent evt) {
                EstadoCambiado(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter(){
            @Override
           public void windowClosing(WindowEvent e){
             setState(NORMAL);
             setVisible(false);
           }
         });

        tarea =  new subTarea(this);

    }

    private void EstadoCambiado(java.awt.event.WindowEvent evt) {                                

        if ( evt.getNewState() == ICONIFIED) {

            try{
                this.setState(NORMAL);
                this.setVisible(false);
            }catch(Exception exe){;}

        }
        
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtEstado = new javax.swing.JTextField();
        btnEstado = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtComandos = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Servidor de Chat v.1");

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/l.png"))); // NOI18N

        jLabel2.setText("Servidor Chat v.1");

        jButton2.setText("Acerca de..");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Modulo"));

        jLabel3.setText("Servidor");

        txtEstado.setBackground(new java.awt.Color(51, 204, 255));
        txtEstado.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        txtEstado.setForeground(new java.awt.Color(255, 0, 0));
        txtEstado.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtEstado.setText("Corriendo..");
        txtEstado.setBorder(null);

        btnEstado.setText("Iniciar");
        btnEstado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEstadoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addComponent(jLabel3)
                .addGap(43, 43, 43)
                .addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE)
                .addComponent(btnEstado))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEstado))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        txtComandos.setColumns(20);
        txtComandos.setEditable(false);
        txtComandos.setFont(new java.awt.Font("Monospaced", 0, 11)); // NOI18N
        txtComandos.setRows(5);
        jScrollPane1.setViewportView(txtComandos);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(76, 76, 76)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton2)
                            .addComponent(jLabel2))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEstadoActionPerformed
       
       if(this.btnEstado.getText().compareTo("Iniciar") == 0){
           //new ServidorChat(this);
           System.out.println("aaaaaaa");
          tarea =  new subTarea(this);
       }  
       else{
            System.out.println("dsdsds");
           tarea.finServidor();
       }
          
        // TODO add your handling code here:
    }//GEN-LAST:event_btnEstadoActionPerformed

    public void escribirComando(String txt){
        this.txtComandos.append(txt);
    }

    public void iniciarServidor(){
        if(this.btnEstado.getText().compareTo("Iniciar") == 0){
           this.txtEstado.setVisible(true);
           this.btnEstado.setText("Parar");
       }
       else{
           this.txtEstado.setVisible(false);
            this.btnEstado.setText("Iniciar");
       }
    }

    private void anadirTrayIcon() {

// Referencia al tray icon, este se construira con un popup

TrayIcon trayIcon;

//    Verificamos si el TryIcon se soporta en el sistema

if (SystemTray.isSupported()) {

//    Recuperamos la barra de trays del sistema

SystemTray tray = SystemTray.getSystemTray();

//    COnstruimos una ImageIcon para la imágen del Tray

ImageIcon imagen = new ImageIcon(getClass().getResource("/img/l.png"));

/*    Definicion de algunas clases que manejen los eventos

*     de los items en el Tray

*

*/

ActionListener eventoSalir = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
};

ActionListener eventoAcercaDe = new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "Luis Angel Torres Calle \n" + "® Diciembre 2009 \n" + "Piura - Peru");
    }
};

ActionListener eventoRestaurar = new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        setVisible(true);
    }
};


//    El popup para desplegar en el TryIcon

PopupMenu popup = new PopupMenu();

//    Construimos los items del popup

MenuItem mi1 = new MenuItem("Restaurar");


MenuItem mi4 = new MenuItem("Salir");

MenuItem mi5 = new MenuItem("Acerca de...");

//    Añadimos los items al popup

popup.add(mi1);


popup.addSeparator();

popup.add(mi5);

popup.addSeparator();

popup.add(mi4);

//    Agragamos los eventos

mi4.addActionListener(eventoSalir);
mi1.addActionListener(eventoRestaurar);
mi5.addActionListener(eventoAcercaDe);

//    Construimos el TrayIcon con la imagen y el popup previamente definidos

trayIcon = new TrayIcon(imagen.getImage(), "Servidor de Chat!!", popup);

trayIcon.setImageAutoSize(true);

try {

tray.add(trayIcon);

} catch (AWTException e) {

System.err.println("El TrayIcon no puede añadirse");

}

}

}
    /**
    * @param args the command line arguments
    */
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEstado;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtComandos;
    private javax.swing.JTextField txtEstado;
    // End of variables declaration//GEN-END:variables
    private subTarea tarea;

}
